package org.jeecg.modules.business.takestockplan.controller;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.business.takestockplan.entity.TakeStockPlanDifference;
import org.jeecg.modules.business.takestockplan.entity.TakeStockPlanDifferenceMaterial;
import org.jeecg.modules.business.takestockplan.entity.VO.TakeStockPlanDifferencePage;
import org.jeecg.modules.business.takestockplan.entity.VO.TakeStockPlanExecuteVO;
import org.jeecg.modules.business.takestockplan.service.ITakeStockPlanDifferenceMaterialService;
import org.jeecg.modules.business.takestockplan.service.ITakeStockPlanDifferenceService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Description: 盘点差异处理单
 * @Author: jeecg-boot
 * @Date: 2023-11-23
 * @Version: V1.0
 */
@Api(tags = "盘点差异处理单")
@RestController
@RequestMapping("/business/takeStockPlanDifference")
@Slf4j
public class TakeStockPlanDifferenceController {
    @Autowired
    private ITakeStockPlanDifferenceService takeStockPlanDifferenceService;
    @Autowired
    private ITakeStockPlanDifferenceMaterialService takeStockPlanDifferenceMaterialService;

    @Value(value = "${wms.config.printUrl.takeStockPlanDifference:}")
    private String url;

    /**
     * 分页列表查询
     *
     * @param takeStockPlanDifference
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "盘点差异处理单-分页列表查询", notes = "盘点差异处理单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<Page<TakeStockPlanExecuteVO>> queryPageList(TakeStockPlanExecuteVO takeStockPlanDifference,
                                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                              HttpServletRequest req) {
        Result<Page<TakeStockPlanExecuteVO>> result = new Result<>();
        Page<TakeStockPlanExecuteVO> pageList = new Page<>(pageNo, pageSize);
        pageList = takeStockPlanDifferenceService.listByPage(pageList, takeStockPlanDifference);
        for (TakeStockPlanExecuteVO record : pageList.getRecords()) {
            record.setUrl(url);
        }
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param takeStockPlanDifferencePage
     * @return
     */
    @AutoLog(value = "盘点差异处理单-添加")
    @ApiOperation(value = "盘点差异处理单-添加", notes = "盘点差异处理单-添加")
    @RequiresPermissions("business:takeStockPlanDifference:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody TakeStockPlanDifferencePage takeStockPlanDifferencePage) {
        TakeStockPlanDifference takeStockPlanDifference = new TakeStockPlanDifference();
        BeanUtils.copyProperties(takeStockPlanDifferencePage, takeStockPlanDifference);
        takeStockPlanDifferenceService.saveMain(takeStockPlanDifference, takeStockPlanDifferencePage.getTakeStockPlanDifferenceMaterialList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param takeStockPlanDifferencePage
     * @return
     */
    @AutoLog(value = "盘点差异处理单-编辑")
    @ApiOperation(value = "盘点差异处理单-编辑", notes = "盘点差异处理单-编辑")
    @RequiresPermissions("business:takeStockPlanDifference:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody TakeStockPlanDifferencePage takeStockPlanDifferencePage) {
        TakeStockPlanDifference takeStockPlanDifference = new TakeStockPlanDifference();
        BeanUtils.copyProperties(takeStockPlanDifferencePage, takeStockPlanDifference);
        TakeStockPlanDifference takeStockPlanDifferenceEntity = takeStockPlanDifferenceService.getById(takeStockPlanDifference.getId());
        if (takeStockPlanDifferenceEntity == null) {
            return Result.error("未找到对应数据");
        }
        takeStockPlanDifferenceService.updateMain(takeStockPlanDifference, takeStockPlanDifferencePage.getTakeStockPlanDifferenceMaterialList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "盘点差异处理单-通过id删除")
    @ApiOperation(value = "盘点差异处理单-通过id删除", notes = "盘点差异处理单-通过id删除")
    @RequiresPermissions("business:takeStockPlanDifference:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        takeStockPlanDifferenceService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "盘点差异处理单-通过id查询", notes = "盘点差异处理单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<TakeStockPlanDifference> queryById(@RequestParam(name = "id", required = true) String id) {
        TakeStockPlanDifference takeStockPlanDifference = takeStockPlanDifferenceService.getById(id);
        if (takeStockPlanDifference == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(takeStockPlanDifference);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "盘点差异处理单-物料主表ID查询", notes = "盘点差异处理单-物料-通主表ID查询")
    @GetMapping(value = "/queryWmsTakeStockPlanDifferenceMaterialByMainId")
    public Result<List<TakeStockPlanDifferenceMaterial>> queryWmsTakeStockPlanDifferenceMaterialListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<TakeStockPlanDifferenceMaterial> wmsTakeStockPlanDifferenceMaterialList = takeStockPlanDifferenceMaterialService.selectByMainId(id);
        return Result.OK(wmsTakeStockPlanDifferenceMaterialList);
    }

    /**
     * 导出excel
     *
     * @param vo
     */
    @PostMapping(value = "/exportXls")
    @ApiOperation(value = "盘点差异处理单-导出excel", notes = "盘点差异处理单-导出excel")
    public ModelAndView exportXls(@RequestBody TakeStockPlanExecuteVO vo) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<TakeStockPlanDifferencePage> list = new ArrayList<TakeStockPlanDifferencePage>();
        Page<TakeStockPlanExecuteVO> pageList = new Page<>(1, 5);
        pageList = takeStockPlanDifferenceService.listByPage(pageList, vo);
        List<TakeStockPlanExecuteVO> vos = pageList.getRecords();
        List<String> ids = vos.stream().map(TakeStockPlanExecuteVO::getId).collect(Collectors.toList());
        List<TakeStockPlanDifferenceMaterial> materials = takeStockPlanDifferenceMaterialService.list(new LambdaQueryWrapper<TakeStockPlanDifferenceMaterial>()
                .in(TakeStockPlanDifferenceMaterial::getTakeStockPlanDifferenceId, ids));
        Map<String, List<TakeStockPlanDifferenceMaterial>> listMap = new HashMap<>();
        if (materials != null){
            listMap = materials.stream().collect(Collectors.groupingBy(TakeStockPlanDifferenceMaterial::getTakeStockPlanDifferenceId));
        }
        for (TakeStockPlanExecuteVO executeVO : vos) {
            TakeStockPlanDifferencePage page = new TakeStockPlanDifferencePage();
            BeanUtils.copyProperties(executeVO, page);
            List<TakeStockPlanDifferenceMaterial> wmsTakeStockPlanDifferenceMaterialList = listMap.get(executeVO.getId());
            page.setTakeStockPlanDifferenceMaterialList(wmsTakeStockPlanDifferenceMaterialList);
            list.add(page);
        }

        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "盘点差异处理单");
        mv.addObject(NormalExcelConstants.CLASS, TakeStockPlanDifferencePage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("盘点差异处理单数据", "导出人:" + sysUser.getRealname(), "盘点差异处理单"));
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @ApiOperation(value = "盘点差异处理单-通过excel导入数据", notes = "盘点差异处理单-通过excel导入数据")
    public Result<List<TakeStockPlanDifferenceMaterial>> importExcel(@RequestPart("file") MultipartFile file, String takeStockPlanId, String takeStockPlanDifferenceId) {
        return takeStockPlanDifferenceService.importExcel(file, takeStockPlanId, takeStockPlanDifferenceId);
    }

    /**
     * 生成盘盈盘亏单
     *
     * @return
     */
    @ApiOperation(value = "盘点差异处理单-生成盘盈盘亏单", notes = "盘点差异处理单-生成盘盈盘亏单")
    @PostMapping(value = "/addTakeStockResult")
    @RequiresPermissions("business:takeStockPlanDifference:edit")
    public Result<String> addTakeStockResult(@RequestParam(name = "id", required = true) String id) {
        takeStockPlanDifferenceService.addTakeStockResult(id);
        return Result.OK("操作成功！");
    }

    /**
     * 保存
     *
     * @param takeStockPlanDifferencePage
     * @return
     */
    @ApiOperation(value = "盘点差异处理单-保存", notes = "盘点差异处理单-保存")
    @RequiresPermissions("business:takeStockPlanDifference:add")
    @PostMapping(value = "/save")
    public Result<String> save(@RequestBody TakeStockPlanDifferencePage takeStockPlanDifferencePage) {
        TakeStockPlanDifference takeStockPlanDifference = new TakeStockPlanDifference();
        if ("2".equals(takeStockPlanDifferencePage.getDocumentStatus())) {
            List<TakeStockPlanDifferenceMaterial> list = takeStockPlanDifferencePage.getTakeStockPlanDifferenceMaterialList();
            for (TakeStockPlanDifferenceMaterial material : list) {
                if (StringUtils.isBlank(material.getRealCount())) {
                    material.setRealCount("0");
                    material.setRealCountAssistant("0");
                    BigDecimal subtract = material.getStockQuantity().subtract(new BigDecimal("0"));
                    if (subtract.compareTo(new BigDecimal("0")) == 0) {
                        material.setResult("4");
                    } else {
                        material.setInventoryLoss(NumberUtil.toStr(subtract));
                        material.setResult("2");
                    }
                }
            }
        }
        if (StringUtils.isBlank(takeStockPlanDifferencePage.getId())) {
            // 新增
            BeanUtils.copyProperties(takeStockPlanDifferencePage, takeStockPlanDifference);
            takeStockPlanDifferenceService.saveMain(takeStockPlanDifference, takeStockPlanDifferencePage.getTakeStockPlanDifferenceMaterialList());
        } else {
            // 编辑
            BeanUtils.copyProperties(takeStockPlanDifferencePage, takeStockPlanDifference);
            TakeStockPlanDifference takeStockPlanDifferenceEntity = takeStockPlanDifferenceService.getById(takeStockPlanDifference.getId());
            if (takeStockPlanDifferenceEntity == null) {
                return Result.error("未找到对应数据");
            }
            takeStockPlanDifferenceService.updateMain(takeStockPlanDifference, takeStockPlanDifferencePage.getTakeStockPlanDifferenceMaterialList());
        }
        return Result.OK("保存成功！");
    }
}
